package org.mdrtwell.jdbc;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import oracle.sql.BLOB;

public class MyBlobTestCase {
	private Connection	conn;

	public Connection getConnection() throws ClassNotFoundException, SQLException {
		if (conn == null) {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.140.73:1521:datadb",
					"testmqsl",
					"testmqsl");
		}
		return conn;
	}

	public int insertImage(String from) throws SQLException, IOException, ClassNotFoundException {
		Connection con = this.getConnection();
		// �����Զ��ύfalse
		conn.setAutoCommit(false);
		Statement sm = conn.createStatement();
		// ������ݣ�Blob�ֶ����գ�ʹ��Empty_BLOB()�����myseq����
		int result = sm.executeUpdate(" insert into myblobtest values(myseq.nextval,Empty_BLOB()) ");
		// ��ѯ�ող������ݣ���������,ʹ��for update�ؼ���
		ResultSet rs = sm.executeQuery(" select image from myblobtest where id = (select max(id) from myblobtest) for update ");
		if (rs.next()) {
			BLOB blob = (BLOB) rs.getBlob(1);
			// ��������
			OutputStream os = blob.getBinaryOutputStream();
			// �������ַ���
			PrintStream printStream = new PrintStream(os);
			// ��������ַ���
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(from));
			// �����ֽڻ���
			byte[] buffer = new byte[400];
			int length = 0;
			while ((length = bis.read(buffer)) > 0) {
				os.write(buffer, 0, length);
			}
			printStream.flush();
			printStream.close();
			bis.close();
		}
		rs.close();
		sm.close();
		con.close();
		return result;
	}

	public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
		MyBlobTestCase blobTest = new MyBlobTestCase();
		blobTest.insertImage("E:\\Dropbox_Data\\My Dropbox\\Photos\\Leah Dizon 511.jpg");
		System.out.println("OK");
	}
}
